//
//  TeamDetailInfoViewController.m
//  NBAPro
//
//  Created by 李广松 on 16/7/11.
//  Copyright © 2016年 WYH. All rights reserved.
//

#import "TeamDetailInfoViewController.h"

@implementation TeamDetailInfoViewController {
    UITableView *playersTableView;
    
    int index;
    
    NSArray *playersArr;
    
    NSDictionary *playersAverageInfoDic;
    
    NSMutableDictionary *ptsDic;
    NSMutableDictionary *rebDic;
    NSMutableDictionary *astDic;
    NSMutableDictionary *minDic;
    NSMutableDictionary *gpDic;
    
}

- (id)initWithTeamId:(NSString *)idStr AndCity:(NSString *)city AndName:(NSString *)name AndIconStr:(NSString *)iconStr AndWin:(NSString *)win AndLose:(NSString *)lose AndConference:(NSString *)conference AndConferenceRank:(NSString *)conferenceRank AndDivision:(NSString *)division AndDivisionRank:(NSString *)divisionRank AndPPGRank:(NSString *)ppgRank AndRPGRank:(NSString *)rpgRank AndAPGRank:(NSString *)apgRank AndOPPGRank:(NSString *)oppgRank {
    
    self = [super init];
    if (self) {
        self.teamDataDic = @{ @"id":idStr, @"city":city, @"name":name, @"icon":iconStr, @"win":win, @"lose":lose, @"conference":conference, @"conferenceRank":conferenceRank, @"division":division, @"divisionRank":divisionRank, @"PPGRank":ppgRank, @"RPGRank":rpgRank, @"APGRank":apgRank, @"OPPGRank":oppgRank };
    }
    
    
    return self;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    index = 0;
    
    [self createDataDic];
    
    self.view.backgroundColor = [UIColor colorWithRed:246/255.0 green:245/255.0 blue:247/255.0 alpha:1];
    
    UIView *titleView = [self createTitleViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    [self.view addSubview:titleView];
    
    UIButton *returnBtn = [self createReturnIconBtnWithFrame:CGRectMake(11, 5, 10.4, 17.4)];
    [self.view addSubview:returnBtn];
    
    UIView *averageView = [self createAverageInfoWithFrame:CGRectMake(0, 150, self.view.frame.size.width, 33)];
    [self.view addSubview:averageView];
    
    
    [self getPlayersInfoWithURL:[[NSString alloc] initWithFormat:@"%@commonteamroster?LeagueID=00&Season=2015-16&TeamID=%@", API_BASE_URL_NBA, self.teamDataDic[@"id"]]];


}


#pragma mark - 获取球队中球员信息
- (void)getPlayersAverageInfoWithURL:(NSString *)urlStr {
    NSURL *url = [[NSURL alloc] initWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            [self performSelectorOnMainThread:@selector(getPlayersAverageInfo:) withObject:result waitUntilDone:YES];
        }
    }];
    
    [dataTask resume];

}

- (void)getPlayersAverageInfo:(NSDictionary *)result {
    index++;
    
    NSString *key = result[@"resultSets"][0][@"rowSet"][0][3];
//    NSArray *arr =  result[@"resultSets"][1][@"rowSet"];
//    
//    if (arr.count != 0) {
//        [self AverageDataSetValueWithDataInfo:result[@"resultSets"][1][@"rowSet"][0][3] AndDic:ptsDic AndKey:key];
//        [self AverageDataSetValueWithDataInfo:result[@"resultSets"][1][@"rowSet"][0][5] AndDic:rebDic AndKey:key];
//        [self AverageDataSetValueWithDataInfo:result[@"resultSets"][1][@"rowSet"][0][4] AndDic:astDic AndKey:key];
//    }
//    else {
//        [self AverageDataSetValueWithDataInfo:@"0" AndDic:ptsDic AndKey:key];
//        [self AverageDataSetValueWithDataInfo:@"0" AndDic:rebDic AndKey:key];
//        [self AverageDataSetValueWithDataInfo:@"0" AndDic:astDic AndKey:key];
//
//    }
    
    @try {
        [self AverageDataSetValueWithDataInfo:result[@"resultSets"][1][@"rowSet"][0][3] AndDic:ptsDic AndKey:key];
        [self AverageDataSetValueWithDataInfo:result[@"resultSets"][1][@"rowSet"][0][5] AndDic:rebDic AndKey:key];
        [self AverageDataSetValueWithDataInfo:result[@"resultSets"][1][@"rowSet"][0][4] AndDic:astDic AndKey:key];

    } @catch (NSException *exception) {
        [self AverageDataSetValueWithDataInfo:@"0" AndDic:ptsDic AndKey:key];
        [self AverageDataSetValueWithDataInfo:@"0" AndDic:rebDic AndKey:key];
        [self AverageDataSetValueWithDataInfo:@"0" AndDic:astDic AndKey:key];

    } @finally {

    }
    
    if (index == playersArr.count) {
        playersTableView = [self createTableViewWithFrame:CGRectMake(0, 150 + 33, self.view.frame.size.width, self.view.frame.size.height - (150 + 33))];
        [self.view addSubview:playersTableView];
    }


}

- (void)AverageDataSetValueWithDataInfo:(NSString *)dataInfo AndDic:(NSDictionary *)dic AndKey:(NSString *)key{
    NSString *dataStr = [[NSString alloc] initWithFormat:@"%@", dataInfo];
    [dic setValue:dataStr forKey:key];
}

- (void)getPlayersInfoWithURL:(NSString *)urlStr {
    NSURL *url = [[NSURL alloc] initWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            [self performSelectorOnMainThread:@selector(getPalyersDetailInfo:) withObject:result waitUntilDone:YES];
        }
    }];
    
    [dataTask resume];
    
}

- (void)getPalyersDetailInfo:(NSDictionary *)result {
    playersArr = result[@"resultSets"][0][@"rowSet"];
    
    for (int i = 0; i < playersArr.count; i++) {
        [self getPlayersAverageInfoWithURL:[[NSString alloc] initWithFormat:@"%@commonplayerinfo?PlayerID=%@", API_BASE_URL_NBA, playersArr[i][12]]];

    }


}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return playersArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *result = playersArr[indexPath.row];
    
    
    NSString *age = [[NSString alloc] initWithFormat:@"%@", playersArr[indexPath.row][9]];
    
    TeamDetailInfoTalbeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[TeamDetailInfoTalbeViewCell alloc] initWithAge:age AndHeight:result[6] AndWeight:result[7] AndPTS:ptsDic[result[3]] AndREB:rebDic[result[3]] AndAST:astDic[result[3]] AndMIN:@"21" AndGP:@"35"];
    }
    NSString *positionAndNumber = [[NSString alloc] initWithFormat:@"%@ %@", result[5], result[4]];
    cell.nameLab.text = result[3];
    cell.positionAndNumberLab.text = positionAndNumber;
  
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@media/players/230x185/%@.png", API_BASE_URL_NBA_BASE, result[result.count - 1]];
    NSURL *imgUrl = [[NSURL alloc] initWithString:urlStr];
    UIImage *headImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:imgUrl] ];
    cell.headImgView.image = headImg;
    cell.headView.layer.borderColor = [GetInfo getTeamColorWithTeamName:self.teamDataDic[@"name"]].CGColor;
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 73;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PlayerInfoViewController *playerInfoViewController = [[PlayerInfoViewController alloc] initWithPlayerId:[[NSString alloc] initWithFormat:@"%@", playersArr[indexPath.row][12]]];
    
    [self.navigationController pushViewController:playerInfoViewController animated:YES];
}


#pragma mark - 界面
- (UIView *)createTitleViewWithFrame:(CGRect)frame{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [GetInfo getTeamColorWithTeamName:self.teamDataDic[@"name"]];
    
    UILabel *teamCityLab = [self createLabelWithFrame:CGRectMake(10, frame.size.height / 2 - 15, 130, 20) AndText:self.teamDataDic[@"city"] AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:16];
    [view addSubview:teamCityLab];
    
    UILabel *teamNameLab = [self createLabelWithFrame:CGRectMake(10, teamCityLab.frame.origin.y + teamCityLab.frame.size.height + 2, 100, 15) AndText:self.teamDataDic[@"name"] AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:13];
    [view addSubview:teamNameLab];
    
    UIImageView *teamIconView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 50, frame.size.height / 2 - 40, 80, 80)];
    teamIconView.image = [UIImage imageNamed:[self.teamDataDic[@"icon"] lowercaseString]];
    [view addSubview:teamIconView];
    
    UILabel *winAndLoseLab = [self createLabelWithFrame:CGRectMake(self.view.frame.size.width - 150, teamCityLab.frame.origin.y - 3, 150, 12) AndText:[[NSString alloc] initWithFormat:@"%@W - %@L", self.teamDataDic[@"win"], self.teamDataDic[@"lose"]] AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:10];
    [view addSubview:winAndLoseLab];
    
    UILabel *regionalLab = [self createLabelWithFrame:CGRectMake(winAndLoseLab.frame.origin.x, winAndLoseLab.frame.origin.y + winAndLoseLab.frame.size.height + 2, 150, 12) AndText:[[NSString alloc] initWithFormat:@"#%@ in the %@ Conference", self.teamDataDic[@"conferenceRank"], self.teamDataDic[@"conference"]] AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:10];
    [view addSubview: regionalLab];
    
    UILabel *divisionLab = [self createLabelWithFrame:CGRectMake(regionalLab.frame.origin.x, regionalLab.frame.origin.y + winAndLoseLab.frame.size.height + 2, 150, 12) AndText:[[NSString alloc] initWithFormat:@"#%@ in the %@ Division", self.teamDataDic[@"divisionRank"], self.teamDataDic[@"division"]] AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:10];
    [view addSubview:divisionLab];
    
    return view;
}

- (UIView *)createAverageInfoWithFrame:(CGRect)frame {
    UIView *averageView = [[UIView alloc] initWithFrame:frame];
    
    UIView *PPGView = [self createOneAverageViewWithFrame:CGRectMake(27, 0, 53, 30) AndText:@"PPG" AndInfo:[[NSString alloc] initWithFormat:@"%@th", self.teamDataDic[@"PPGRank"]]];
    [averageView addSubview:PPGView];
    
    UIView *RPGView = [self createOneAverageViewWithFrame:CGRectMake(PPGView.frame.origin.x + PPGView.frame.size.width + 50, 0, 53, 30) AndText:@"RPG" AndInfo:[[NSString alloc] initWithFormat:@"%@th", self.teamDataDic[@"PPGRank"]]];
    [averageView addSubview:RPGView];
    
    UIView *APGView = [self createOneAverageViewWithFrame:CGRectMake(RPGView.frame.origin.x + RPGView.frame.size.width + 50, 0, 53, 30) AndText:@"RPG" AndInfo:[[NSString alloc] initWithFormat:@"%@th", self.teamDataDic[@"RPGRank"]]];
    [averageView addSubview:APGView];
    
    UIView *OPPGView = [self createOneAverageViewWithFrame:CGRectMake(APGView.frame.origin.x + APGView.frame.size.width + 50, 0, 55, 30) AndText:@"OPPG" AndInfo:[[NSString alloc] initWithFormat:@"%@th", self.teamDataDic[@"OPPGRank"]]];
    [averageView addSubview:OPPGView];
    
    
    return averageView;
}

- (UIView *)createOneAverageViewWithFrame:(CGRect)frame AndText:(NSString *)text AndInfo:(NSString *)info {
    UIView *averageView = [[UIView alloc] initWithFrame:frame];
    
    CGSize textSize = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10]}];
    UILabel *averageLab = [CreateControl createLabelWithFrame:CGRectMake(0, 20, textSize.width, 10) AndText:text AndTextColor:[UIColor colorWithRed:174/255.0 green:180/255.0 blue:192/255.0 alpha:1]  AndBackgroundColor:[UIColor clearColor] AndTextFont:10];
    [averageView addSubview:averageLab];
    
    CGSize infoSize = [info sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    UILabel *averageInfoLab = [CreateControl createLabelWithFrame:CGRectMake(averageLab.frame.size.width + 2, 15, infoSize.width, 15) AndText:info AndTextColor:[UIColor colorWithRed:105/255.0 green:117/255.0 blue:140/255.0 alpha:1] AndBackgroundColor:[UIColor clearColor] AndTextFont:15];
    [averageView addSubview:averageInfoLab];
    
    return averageView;

}

- (UITableView *)createTableViewWithFrame:(CGRect)frame {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor colorWithRed:246/255.0 green:245/255.0 blue:247/255.0 alpha:1];

    
    return tableView;

}

- (UIButton *)createReturnIconBtnWithFrame:(CGRect)frame {
    UIButton *returnBtn = [[UIButton alloc] initWithFrame:frame];
    [returnBtn setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [returnBtn addTarget:self action:@selector(touchReturn) forControlEvents:UIControlEventTouchUpInside];
    
    return returnBtn;
}


- (UILabel *)createLabelWithFrame:(CGRect)frame AndText:(NSString *)text AndTextColor:(UIColor *)textColor AndBackgroundColor:(UIColor *)backgroundColor AndTextFont:(float)font {
    
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.textColor = textColor;
    label.font = [UIFont systemFontOfSize:font];
    label.backgroundColor = backgroundColor;
    label.textAlignment = NSTextAlignmentLeft;
    
    return label;
}
- (void)createDataDic {
    ptsDic = [[NSMutableDictionary alloc] init];
    rebDic = [[NSMutableDictionary alloc] init];
    astDic = [[NSMutableDictionary alloc] init];
    gpDic = [[NSMutableDictionary alloc] init];
}


#pragma mark - 其他
- (void)touchReturn {
    [self.navigationController popViewControllerAnimated:YES];
}


- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
